<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="90px"
    >
      <el-form-item label="費用編碼" prop="costCode">
        <el-input
          v-model="queryParams.costCode"
          placeholder="請輸入費用編碼"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="費用標題" prop="costTitle">
        <el-input
          v-model="queryParams.costTitle"
          placeholder="請輸入費用標題"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="費用來源" prop="costSource">
        <el-select
          v-model="queryParams.costSource"
          placeholder="請選擇費用來源"
          clearable
        >
          <el-option
            v-for="dict in dict.type.cost_source"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="供應商名稱" prop="supplierName">
        <el-input
          v-model="queryParams.supplierName"
          placeholder="請輸入供應商名稱"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="時間範圍" prop="time">
        <el-date-picker
          v-model="timeData"
          type="datetimerange"
          value-format="yyyy-MM-dd"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        >
        </el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['biz:cost:add']"
          >新增</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['biz:cost:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['biz:cost:remove']"
          >删除</el-button
        >
      </el-col> -->
      <el-col :span="1.5">
        <!-- <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['biz:cost:export']"
          >導出</el-button
        > -->
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['biz:cost:export']"
          >導出</el-button
        >
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport_item"
          v-hasPermi="['biz:cost:export']"
          >生成費用報表</el-button
        >
      </el-col>
      <el-popover
        style="float: right; margin-left: 5px"
        placement="bottom-start"
        width="100"
        trigger="click"
      >
        <div>
          <el-checkbox-group
            v-model="checked_header"
            @change="Checked_header_list"
          >
            <el-checkbox
              :disabled="item.disabled"
              v-for="item in header_list"
              :label="item.prop"
              :key="item.prop"
              >{{ item.name }}</el-checkbox
            >
          </el-checkbox-group>
        </div>
        <el-button slot="reference" size="mini" circle icon="el-icon-setting" />
      </el-popover>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="costList"
      @selection-change="handleSelectionChange"
    >
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column
        v-if="checked_header.includes('costCode')"
        label="費用編碼"
        align="center"
        prop="costCode"
      />
      <el-table-column
        v-if="checked_header.includes('costTitle')"
        label="費用標題"
        align="center"
        prop="costTitle"
      />
      <el-table-column
        v-if="checked_header.includes('costSource')"
        label="費用來源"
        align="center"
        prop="costSource"
      >
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.cost_source"
            :value="scope.row.costSource"
          />
        </template>
      </el-table-column>
      <el-table-column
        v-if="checked_header.includes('costAmount')"
        label="金額"
        align="center"
        prop="costAmount"
      >
      </el-table-column>
      <el-table-column
        v-if="checked_header.includes('supplierName')"
        label="供應商名稱"
        align="center"
        prop="supplierName"
      />
      <el-table-column
        v-if="checked_header.includes('costStatus')"
        label="費用狀態"
        align="center"
        prop="costStatus"
      >
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.cost_status"
            :value="scope.row.costStatus"
          />
        </template>
      </el-table-column>

      <el-table-column
        label="付款時間"
        v-if="checked_header.includes('payTime')"
        align="center"
        prop="payTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.payTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['biz:cost:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['biz:cost:remove']"
            >删除</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleDetail(scope.row)"
            >詳情</el-button
          >
          <el-button
            size="mini"
            type="text"
            :disabled="scope.row.costStatus == 50 || scope.row.costStatus == 40||scope.row.costStatus == 10"
            icon="el-icon-refresh-left"
            @click="costCancel(scope.row)"
            v-hasPermi="['biz:cost:cancel']"
            >撤回</el-button
          >
          <div>
            <el-button
              style="padding: 5px"
              size="mini"
              :disabled="scope.row.costStatus != 30"
              v-hasPermi="['biz:cost:payment']"
              type="primary"
              @click="costPay(scope.row)"
              >付款</el-button
            >
          </div>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 確認收款款 -->
    <el-dialog :visible.sync="open_payInvoice" width="400px" append-to-body>
      <el-form
        ref="form_payInvoice"
        :model="form_payInvoice"
        :rules="rules_payInvoice"
        label-width="80px"
      >
        <el-form-item label="付款時間" prop="payTime">
          <el-date-picker
            clearable
            v-model="form_payInvoice.payTime"
            @input="$forceUpdate()"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="請選付款時間"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div style="text-align: center">
        <el-button type="primary" @click="submitForm_payInvoice"
          >確 定</el-button
        >
        <el-button @click="cancel_payInvoice">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 添加或修改費用对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="費用編碼" prop="costCode">
          <el-input v-model="form.costCode" placeholder="請輸入費用編碼" />
        </el-form-item>
        <el-form-item label="費用標題" prop="costTitle">
          <el-input v-model="form.costTitle" placeholder="請輸入費用標題" />
        </el-form-item>
        <el-form-item label="費用來源" prop="costSource">
          <el-select v-model="form.costSource" placeholder="請選擇費用來源">
            <el-option
              v-for="dict in dict.type.cost_source"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="支出賬號" prop="costBankNo">
          <el-input v-model="form.costBankNo" placeholder="請輸入支出賬號" />
        </el-form-item>
        <el-form-item label="支出銀行名稱" prop="costBankName">
          <el-input
            v-model="form.costBankName"
            placeholder="請輸入支出銀行名稱"
          />
        </el-form-item>
        <el-form-item label="支出賬戶名稱" prop="costBankAccount">
          <el-input
            v-model="form.costBankAccount"
            placeholder="請輸入支出賬戶名稱"
          />
        </el-form-item>
        <el-form-item label="支出金額" prop="costAmount">
          <el-input v-model="form.costAmount" placeholder="請輸入支出金額" />
        </el-form-item>
        <el-form-item label="稅金" prop="taxAmount">
          <el-input v-model="form.taxAmount" placeholder="請輸入稅金" />
        </el-form-item>
        <el-form-item label="支出金額" prop="costTaxAmount">
          <el-input v-model="form.costTaxAmount" placeholder="請輸入支出金額" />
        </el-form-item>
        <el-form-item label="供應商編碼" prop="supplierCode">
          <el-input
            v-model="form.supplierCode"
            placeholder="請輸入供應商編碼"
          />
        </el-form-item>
        <el-form-item label="供應商名稱" prop="supplierName">
          <el-input
            v-model="form.supplierName"
            placeholder="請輸入供應商名稱"
          />
        </el-form-item>
        <el-form-item label="備註" prop="remark">
          <el-input v-model="form.remark" placeholder="請輸入備註" />
        </el-form-item>
        <el-form-item label="經辦人ID" prop="operatorId">
          <el-input v-model="form.operatorId" placeholder="請輸入經辦人ID" />
        </el-form-item>
        <el-form-item label="經辦人" prop="operatorName">
          <el-input v-model="form.operatorName" placeholder="請輸入經辦人" />
        </el-form-item>
        <el-form-item label="付款時間" prop="payTime">
          <el-date-picker
            clearable
            v-model="form.payTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="請選擇付款時間"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="收款賬號" prop="toBankNo">
          <el-input v-model="form.toBankNo" placeholder="請輸入收款賬號" />
        </el-form-item>
        <el-form-item label="收款銀行" prop="toBankName">
          <el-input v-model="form.toBankName" placeholder="請輸入收款銀行" />
        </el-form-item>
        <el-form-item label="收款賬戶" prop="toBankAccount">
          <el-input v-model="form.toBankAccount" placeholder="請輸入收款賬戶" />
        </el-form-item>
        <el-divider content-position="center">費用明細信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="mini"
              @click="handleAddBizCostItem"
              >添加</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="handleDeleteBizCostItem"
              >删除</el-button
            >
          </el-col>
        </el-row>
        <el-table
          :data="bizCostItemList"
          :row-class-name="rowBizCostItemIndex"
          @selection-change="handleBizCostItemSelectionChange"
          ref="bizCostItem"
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column
            label="序號"
            align="center"
            prop="index"
            width="50"
          />
          <el-table-column label="費用編碼" prop="costCode" width="150">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.costCode"
                placeholder="請輸入費用編碼"
              />
            </template>
          </el-table-column>
          <el-table-column label="費用項目" prop="costItem" width="150">
            <template slot-scope="scope">
              <el-select
                v-model="scope.row.costItem"
                placeholder="請選擇費用項目"
              >
                <el-option
                  v-for="dict in dict.type.business_scope"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="費用項目" prop="costItemName" width="150">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.costItemName"
                placeholder="請輸入費用項目"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="費用項目分類KEY"
            prop="costItemType"
            width="150"
          >
            <template slot-scope="scope">
              <el-select
                v-model="scope.row.costItemType"
                placeholder="請選擇費用項目分類KEY"
              >
                <el-option
                  v-for="dict in dict.type.business_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column
            label="費用項目分類"
            prop="costItemTypeName"
            width="150"
          >
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.costItemTypeName"
                placeholder="請輸入費用項目分類"
              />
            </template>
          </el-table-column>
          <el-table-column label="支出金額" prop="costAmount" width="150">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.costAmount"
                placeholder="請輸入支出金額"
              />
            </template>
          </el-table-column>
          <el-table-column label="稅率" prop="tax" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.tax" placeholder="請輸入稅率" />
            </template>
          </el-table-column>
          <el-table-column label="稅金" prop="taxAmount" width="150">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.taxAmount"
                placeholder="請輸入稅金"
              />
            </template>
          </el-table-column>
          <el-table-column label="支出金額" prop="costTaxAmount" width="150">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.costTaxAmount"
                placeholder="請輸入支出金額"
              />
            </template>
          </el-table-column>
          <el-table-column label="備註" prop="remark" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.remark" placeholder="請輸入備註" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">確 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listCost,
  getCost,
  delCost,
  addCost,
  updateCost,
  cancelCost,
  payCost,
} from "@/api/biz/cost";

export default {
  name: "Cost",
  dicts: ["business_scope", "cost_source", "business_type", "cost_status"],
  data() {
    return {
      timeData: [
        this.$moment().subtract(1, "years").format("YYYY-MM-DD"),
        this.$moment().format("YYYY-MM-DD"),
      ],
      // 遮罩层
      loading: true,
      // 选中數組
      ids: [],
      // 子表选中數据
      checkedBizCostItem: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 顯示搜索条件
      showSearch: true,
      // 总条數
      total: 0,
      // 費用表格數据
      costList: [],
      // 費用明細表格數据
      bizCostItemList: [],
      // 弹出层標题
      title: "",
      // 是否顯示弹出层
      open: false,
      // 查询參數
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        costCode: null,
        costTitle: null,
        costSource: null,
        supplierName: null,
        orderByColumn: "update_time",
        isAsc: "desc",
      },
      // 表单參數
      form: {},
      // 表单校验
      rules: {
        costBankId: [
          { required: true, message: "支出賬戶id不能為空", trigger: "change" },
        ],
        costBankNo: [
          { required: true, message: "支出賬號不能為空", trigger: "blur" },
        ],
        costBankName: [
          { required: true, message: "支出銀行名稱不能為空", trigger: "blur" },
        ],
        costAmount: [
          { required: true, message: "支出金額不能為空", trigger: "blur" },
        ],
        taxAmount: [
          { required: true, message: "稅金不能為空", trigger: "blur" },
        ],
        costTaxAmount: [
          { required: true, message: "支出金額不能為空", trigger: "blur" },
        ],
      },
      header_list: [
        {
          name: "費用編碼",
          disabled: true,
          prop: "costCode",
        },
        {
          name: "費用標題",
          disabled: true,
          prop: "costTitle",
        },
        {
          name: "費用來源",
          disabled: false,
          prop: "costSource",
        },
        {
          name: "金額",
          disabled: false,
          prop: "costAmount",
        },
        {
          name: "供應商名稱",
          disabled: false,
          prop: "supplierName",
        },
        {
          name: "付款狀態",
          disabled: false,
          prop: "costStatus",
        },
        {
          name: "付款時間",
          disabled: false,
          prop: "payTime",
        },
      ],

      checked_header: [
        "costCode",
        "costTitle",
        "costSource",
        "costAmount",
        "costStatus",
        "payTime",
      ],
      open_payInvoice: false,
      form_payInvoice: {},
      rules_payInvoice: {},
    };
  },
  created() {
    console.log(111);
    console.log(this.$route.query);
    if (this.$route.query) {
      this.queryParams.supplierName = this.$route.query.supplierName;
    }
    this.getList();
  },
  methods: {
    // 付款
    costPay(item) {
      console.log(item);
      this.form_payInvoice.payTime = "";
      this.open_payInvoice = true;

      this.form_payInvoice.id = item.id;
      this.form_payInvoice.payAmount = item.costTaxAmount;
      this.form_payInvoice.remark = item.remark;
    },
    submitForm_payInvoice() {
      payCost({
        id: this.form_payInvoice.id,
        amount: this.form_payInvoice.payAmount,
        payTime: this.form_payInvoice.payTime,
        remark: this.form_payInvoice.remark,
      }).then((response) => {
        if (response.code == 200) {
          this.$modal.msgSuccess("付款成功");
          this.cancel_payInvoice();
          this.getList();
        }
      });
    },
    cancel_payInvoice() {
      this.open_payInvoice = false;
    },

    Checked_header_list(list) {
      console.log(this.checked_header);
    },
    /** 查询費用列表 */
    getList() {
      this.loading = true;
      listCost(this.queryParams).then((response) => {
        this.costList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        costCode: null,
        costTitle: null,
        costSource: null,
        costSourceName: null,
        costBankId: null,
        costBankNo: null,
        costBankName: null,
        costBankAccount: null,
        costAmount: null,
        taxAmount: null,
        costTaxAmount: null,
        supplierId: null,
        supplierCode: null,
        supplierName: null,
        remark: null,
        operatorId: null,
        operatorName: null,
        costStatus: null,
        payTime: null,
        toBankId: null,
        toBankNo: null,
        toBankName: null,
        toBankAccount: null,
        delFlag: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
      };
      this.bizCostItemList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      // startDate
      // endDate
      this.queryParams.startDate = this.timeData[0];
      this.queryParams.endDate = this.timeData[1];
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中數据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.$router.push({ path: "/cost/cost/add" });
      // this.open = true;
      // this.title = "添加費用";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      this.$router.push({
        path: "/cost/cost/edit",
        query: { id: id, costStatus: row.costStatus },
      });
    },
    handleDetail(row) {
      const id = row.id || this.ids;
      this.$router.push({
        path: "/cost/cost/detail",
        query: { id: id, costStatus: row.costStatus },
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.bizCostItemList = this.bizCostItemList;
          if (this.form.id != null) {
            updateCost(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCost(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否確認删除費用編號為"' + ids + '"的數据项？')
        .then(function () {
          return delCost(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },

    costCancel(row) {
      const ids = row.id || this.ids;
      let that = this;
      this.$modal
        .confirm('是否確認撤回費用單編號為"' + ids + '"的數据项？')
        .then(function () {
          cancelCost({
            id: ids,
            amount: "",
            payTime: "",
            remark: "",
          }).then((response) => {
            if (response.code == 200) {
              that.$modal.msgSuccess("撤回成功");
              that.getList();
            }
          });
        })
        .catch(() => {});
    },
    /** 費用明細序號 */
    rowBizCostItemIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 費用明細添加按钮操作 */
    handleAddBizCostItem() {
      let obj = {};
      obj.costCode = "";
      obj.costItem = "";
      obj.costItemName = "";
      obj.costItemType = "";
      obj.costItemTypeName = "";
      obj.costAmount = "";
      obj.tax = "";
      obj.taxAmount = "";
      obj.costTaxAmount = "";
      obj.remark = "";
      this.bizCostItemList.push(obj);
    },
    /** 費用明細删除按钮操作 */
    handleDeleteBizCostItem() {
      if (this.checkedBizCostItem.length == 0) {
        this.$modal.msgError("請先選擇要删除的費用明細數据");
      } else {
        const bizCostItemList = this.bizCostItemList;
        const checkedBizCostItem = this.checkedBizCostItem;
        this.bizCostItemList = bizCostItemList.filter(function (item) {
          return checkedBizCostItem.indexOf(item.index) == -1;
        });
      }
    },
    /** 复选框选中數据 */
    handleBizCostItemSelectionChange(selection) {
      this.checkedBizCostItem = selection.map((item) => item.index);
    },
    /** 導出按钮操作 */
    handleExport() {
      this.queryParams.startDate = this.timeData[0];
      this.queryParams.endDate = this.timeData[1];
      // 提交時間
      // startDate
      // endDate
      this.download(
        "biz/cost/export",
        {
          // startDate:this.timeData[0],
          // endDate:this.timeData[1],
          // startPayDate:this.timeData[0],
          // endPayDate:this.timeData[1],
          ...this.queryParams,
        },
        `費用_${new Date().getTime()}.xlsx`
      );
    },
    handleExport_item() {
      this.queryParams.startDate = this.timeData[0];
      this.queryParams.endDate = this.timeData[1];
      // 提交時間
      // startDate
      // endDate
      this.download(
        "biz/cost/item/export",
        {
          // startDate:this.timeData[0],
          // endDate:this.timeData[1],
          // startPayDate:this.timeData[0],
          // endPayDate:this.timeData[1],
          ...this.queryParams,
        },
        `費用報表_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
